/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * tablero.java
 *
 * Created on 18/03/2011, 15:19:05
 */

package gui;

import busquedaAmplitud.NodoA;
import busquedaAmplitud.busquedaAmplitudA;
import busquedaEstrella.NodoE;
import busquedaEstrella.busquedaEstrella;
import busquedaProfundidad.Nodo;
import busquedaProfundidad.busquedaProfundidad;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JOptionPane;
import busquedaProfundidad.matrizAleatoria;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 *
 * @author fabio
 */
public class tableroAjedrez extends javax.swing.JFrame implements MouseListener, MouseMotionListener{

    //Variables globales para detener las busquedas
    busquedaProfundidad buscarP;
    busquedaAmplitudA buscarA;
    busquedaEstrella buscarE;

    boolean personalizada; //BANDERA OPCIONES PERSONALIZADAS
    boolean aleatoria; // BANDERA GENERCACION ALEATORIA DE CABALLOS
    boolean seGenero; //BANDERA QUE IMPIDE SEGUIR MODIFICANDO EL TABLERO
    
    //Para pintar los caballos y manejar los eventos
    boolean caballoBco; //BANDERA QUE INDICA QUE SE PUEDE PINTAR CABALLOS BLANCOS
    boolean caballoNgo; //BANDERA QUE INDICA QUE SE PUEDE PINTAR EL CABALLO NEGRO

    JPanelImage[][] Cuadro; //VARIABLE QUE REPRESENTA UN CUADRO DEL TABLERO

    int cantidadCaballosBlancos; //VARIABLE PARA HACER EL SEGUIMIENTO DE LA CANT DE CABALLOS NEGROS

    //VALORES DEL CABALLO NEGRO GUARDADOS
    int xcn;
    int xcb;

    //MATRIZ QUE REPRESENTA AL TABLERO DE AJEDREZ EN FORMA LOGICA
        //0: CASILLA VACIA
        //1: CASILLA CON UN CABALLO BLANCO
        //2: CASILLA CON UN CABALLO NEGRO
     int [][] matrizTablero;

     boolean detener = false; // para saber si se desea para la busqueda
     int cantNivelesBusqueda = 0;

     public tableroAjedrez() {
        initComponents();
        this.setLocationRelativeTo(null);
        this.setResizable(false);

        //Inicializamos banderas, variables y componentes del form.
        this.jLabel2.setVisible(false);
        this.personalizada = false;
        this.aleatoria = false;
        this.seGenero = false;
        this.caballoBco = false;
        this.caballoNgo = false;
        this.jButton2.setEnabled(false);
        this.xcb = 0;
        this.xcn = 0;
        this.cantidadCaballosBlancos = 0;
        this.butGenerar.setEnabled(false);
        this.butSolucion.setEnabled(false);
        this.tableroPanel.setName("Tablero");
        
        //Pintamos el tablero de ajedrez sin los caballos
        GridLayout layout = new GridLayout();
        layout.setRows(8);
        layout.setColumns(8);
        layout.setHgap(1);
        layout.setVgap(1);
        this.tableroPanel.setLayout(layout);
        Cuadro = new JPanelImage[8][8];

        //Ahora pintamos el tablero sobre el panel
        for(int x=0;x<8;x++){
            for(int y=0;y<8;y++){

                if(x%2==0){
                    if(y%2!=0)
                    {
                    Cuadro[x][y]=new JPanelImage();
                    Cuadro[x][y].caballo_blanco("cuadronegro");
                    Cuadro[x][y].addMouseListener(this);                   
                    this.tableroPanel.add(Cuadro[x][y]);
                    }
                    else
                    {
                    Cuadro[x][y]=new JPanelImage();
                    Cuadro[x][y].caballo_blanco("cuadroblanco");
                    Cuadro[x][y].addMouseListener(this);
                    this.tableroPanel.add(Cuadro[x][y]);
                    }

                }else{
                    if(y%2==0)
                    {
                    Cuadro[x][y]=new JPanelImage();
                    Cuadro[x][y].caballo_blanco("cuadronegro");
                    Cuadro[x][y].addMouseListener(this);                 
                    this.tableroPanel.add(Cuadro[x][y]);
                    }
                    else
                    {
                    Cuadro[x][y]=new JPanelImage();
                    Cuadro[x][y].caballo_blanco("cuadroblanco");
                    Cuadro[x][y].addMouseListener(this);                  
                    this.tableroPanel.add(Cuadro[x][y]);

                    }
                }
            }
        }

        //Inicializamos la matriz
        this.matrizTablero = new int[8][8];
        for(int i=0;i<8;i++){
            for(int j=0;j<8;j++){

                this.matrizTablero[i][j] = 0;
            }
        }
        
        //aca deshabilitamos los componentes que no se deben poder ocupar
        this.butListo.setEnabled(false);
        this.butSolucion.setEnabled(false);
        this.comboAlg.setEnabled(false);
        this.jRadioButton1.setEnabled(false);
        this.jRadioButton2.setEnabled(false);
        this.jTextField1.setEnabled(false);
    }

   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        tableroPanel = new javax.swing.JPanel();
        butSolucion = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel6 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        butGenerar = new javax.swing.JButton();
        radAleatorio = new javax.swing.JRadioButton();
        radPersonalizado = new javax.swing.JRadioButton();
        butListo = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        comboAlg = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Algoritmos de Búsqueda Sistemática y Heurística");

        tableroPanel.setBackground(new java.awt.Color(102, 102, 102));
        tableroPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51)));
        tableroPanel.setToolTipText("Tablero");
        tableroPanel.setPreferredSize(new java.awt.Dimension(400, 400));

        javax.swing.GroupLayout tableroPanelLayout = new javax.swing.GroupLayout(tableroPanel);
        tableroPanel.setLayout(tableroPanelLayout);
        tableroPanelLayout.setHorizontalGroup(
            tableroPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 398, Short.MAX_VALUE)
        );
        tableroPanelLayout.setVerticalGroup(
            tableroPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 398, Short.MAX_VALUE)
        );

        butSolucion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/iconos/ok.png"))); // NOI18N
        butSolucion.setText("Obtener Solución");
        butSolucion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butSolucionActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel6.setForeground(new java.awt.Color(255, 51, 102));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Generación de Caballos"));

        butGenerar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/iconos/generar.png"))); // NOI18N
        butGenerar.setText("Generar");
        butGenerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butGenerarActionPerformed(evt);
            }
        });

        radAleatorio.setText("Aleatorio");
        radAleatorio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radAleatorioActionPerformed(evt);
            }
        });

        radPersonalizado.setText("Personalizado...");
        radPersonalizado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radPersonalizadoActionPerformed(evt);
            }
        });

        butListo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/iconos/ok.png"))); // NOI18N
        butListo.setText("Listo!");
        butListo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butListoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(radPersonalizado)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(butListo, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                            .addComponent(radAleatorio)
                            .addGap(37, 37, 37)
                            .addComponent(butGenerar))))
                .addContainerGap(75, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radAleatorio)
                    .addComponent(butGenerar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(radPersonalizado)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addComponent(butListo)
                .addContainerGap())
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccionar Algoritmo"));

        comboAlg.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione", "Primero en Profundidad", "Primero en Amplitud", "A *", " " }));
        comboAlg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboAlgActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(comboAlg, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(81, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(comboAlg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/loader.gif"))); // NOI18N
        jLabel2.setText("Ejecutando...");

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccione la cantidad de niveles a explorar"));

        jRadioButton1.setText("Todos");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });

        jRadioButton2.setText("Cantidad:");
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton2ActionPerformed(evt);
            }
        });

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jRadioButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jRadioButton1))
                .addContainerGap(128, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(jRadioButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButton2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(11, Short.MAX_VALUE))
        );

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/iconos/exit.png"))); // NOI18N
        jButton1.setText("Salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/iconos/stop.png"))); // NOI18N
        jButton2.setText("Parar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addGap(10, 10, 10)
                            .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(230, 230, 230)
                            .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addContainerGap(10, Short.MAX_VALUE)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(96, 96, 96)
                                        .addComponent(jLabel2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addContainerGap()
                                    .addComponent(butSolucion)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(22, 22, 22)))
                            .addComponent(tableroPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(33, 33, 33))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(butSolucion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(tableroPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(68, 68, 68)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 11, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jMenu1.setText("Archivo");

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
        jMenuItem2.setText("Nuevo");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem3.setText("Acerca de...");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, 0));
        jMenuItem1.setText("Salir");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 463, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void butGenerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butGenerarActionPerformed

        //Generamos la configuracion del tablero en forma aleatoria
        if(this.aleatoria){
            matrizAleatoria mat = new matrizAleatoria();
            //false: aleatoria la posicion del caballo negro
            mat.cargarAleatoriamente(false, 0);
            int[][] ubicaciones;
            ubicaciones = new int[8][8];
            ubicaciones = mat.getMatriz();
                for(int i=0;i<8;i++){
                    for(int j=0;j<8;j++){
                        if(ubicaciones[i][j]==1){
                            this.Cuadro[i][j].caballo_blanco("caballo_blanco");
                            //PONEMOS UN 1 EN MATRIZTABLERO PARA INDICAR UN CABALLO BCO
                            this.matrizTablero[i][j] = 1;
                            this.Cuadro[i][j].repaint();
                    }
                    if(ubicaciones[i][j]==2){
                        this.Cuadro[i][j].caballo_blanco("caballo_negro");
                        //PONEMOS UN 2 EN MATRIZTABLERO PARA INDIAR UN CABALLO NGRO
                        this.matrizTablero[i][j]=2;
                        this.Cuadro[i][j].repaint();
                    }

                   }
              }
                this.tableroPanel.repaint();
        }else{

        }
        this.butGenerar.setEnabled(false);
        this.butListo.setEnabled(true);
        //this.butSolucion.setEnabled(true);
        this.radPersonalizado.setEnabled(false);
        this.radAleatorio.setEnabled(false);
        this.seGenero = true;

    }//GEN-LAST:event_butGenerarActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void comboAlgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboAlgActionPerformed

        this.jButton2.setEnabled(false);
        if(this.comboAlg.getSelectedIndex()==0){
            this.butSolucion.setEnabled(false);
            this.jRadioButton1.setEnabled(false);
            this.jRadioButton2.setEnabled(false);
            this.jTextField1.setEnabled(false);

        }
        if(this.comboAlg.getSelectedIndex()==1){
            this.butSolucion.setEnabled(true);
            this.jRadioButton1.setEnabled(true);
            this.jRadioButton2.setEnabled(true);
            this.jTextField1.setEnabled(false);
            
        }
        if(this.comboAlg.getSelectedIndex()==2){
            this.butSolucion.setEnabled(true);
            this.jRadioButton1.setEnabled(true);
            this.jRadioButton2.setEnabled(true);
            this.jTextField1.setEnabled(false);
            
        }
        if(this.comboAlg.getSelectedIndex()==3){
            this.butSolucion.setEnabled(true);
            this.jRadioButton1.setEnabled(false);
            this.jRadioButton2.setEnabled(false);
            this.jTextField1.setEnabled(false);
            
        }

    }//GEN-LAST:event_comboAlgActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // TODO add your handling code here:
        this.dispose();
        tableroAjedrez abrir = new tableroAjedrez();
        abrir.show(true);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void butSolucionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butSolucionActionPerformed
        
        //Aca se instancian las clases para hacer la busqueda
        if(this.jRadioButton1.isSelected()==false && this.jRadioButton2.isSelected()==false && this.comboAlg.getSelectedIndex()!=3 ){
            //CONTROL DE SELECCION DE MODO DE BUSQUEDA CON O SIN NIVEL TOPE
            JOptionPane.showMessageDialog(null, "Debe seleccionar como se explorarán los niveles");

        }else{

        this.jButton2.setEnabled(true);
        this.jLabel2.setVisible(true);
        this.butSolucion.setEnabled(false);
        this.jRadioButton1.setEnabled(false);
        this.jRadioButton2.setEnabled(false);
        this.jTextField1.setEnabled(false);
        this.comboAlg.setEnabled(false);
        if(this.comboAlg.getSelectedIndex()==1){

            //BUSQUEDA EN PROFUNDIDAD
                //USAMOS UN THREAD PARA EVITAR QUE SE CONGELEN LOS CONTROLES DEL FRAME
            Thread hiloDeLaBusqueda = new Thread(){
                public void run(){
                    if(jRadioButton2.isSelected()){
                    cantNivelesBusqueda = Integer.parseInt(jTextField1.getText());
                    JOptionPane.showMessageDialog(null, "La búsqueda se hara hasta el nivel "+cantNivelesBusqueda);
                    }
                    Nodo inicial = new Nodo(matrizTablero);
                    buscarP = new busquedaProfundidad(inicial, cantNivelesBusqueda);
                     try {
                     buscarP.buscarEnProfundidad();
                     List<int[]> posiciones;
                     posiciones = recorridoEfectuado(buscarP.getCamino());
                     solucionBusqueda abrir = new solucionBusqueda(matrizTablero,posiciones,"Busqueda en Profundidad",1, buscarP.getProfundidadMaxima(), buscarP.getCantidadNodosGenerados(), buscarP.getTiempoTotalBusqueda(),buscarP.isEncontroSolucion(),buscarP.getNivelSolucion(),buscarP.getCostoFinal());
                     abrir.show(true);
                     jButton2.setEnabled(false);
                     jLabel2.setVisible(false);
                     butSolucion.setEnabled(true);
                     jRadioButton1.setEnabled(true);
                     jRadioButton2.setEnabled(true);
                     jTextField1.setEnabled(true);
                     comboAlg.setEnabled(true);
                     } catch (ExcepcionParada ex) {
                     System.out.println(ex.getMessage());
                     jLabel2.setVisible(false);
                     List<int[]> posiciones;
                     posiciones = recorridoEfectuado(buscarP.getCamino());
                     solucionBusqueda abrir = new solucionBusqueda(matrizTablero,posiciones,"Busqueda en Profundidad",1, buscarP.getProfundidadMaxima(), buscarP.getCantidadNodosGenerados(), buscarP.getTiempoTotalBusqueda(),buscarP.isEncontroSolucion(),buscarP.getNivelSolucion(),buscarP.getCostoFinal());
                     abrir.show(true);
                     this.suspend();
                     }
                 
                }
            };
            hiloDeLaBusqueda.start();
        }

        if(this.comboAlg.getSelectedIndex()==2){

            //BUSQUEDA EN AMPLITUD
            Thread hiloDeLaBusqueda = new Thread(){
                public void run(){
                    if(jRadioButton2.isSelected()){
                        cantNivelesBusqueda = Integer.parseInt(jTextField1.getText());
                        JOptionPane.showMessageDialog(null, "La búsqueda se hara hasta el nivel "+cantNivelesBusqueda);
                    }
                    NodoA inicial = new NodoA(matrizTablero,0,0,0);
                    buscarA = new busquedaAmplitudA(inicial, cantNivelesBusqueda);
                try {
                  buscarA.buscarAmplitud();
                  List<int[]> posiciones;
                  posiciones = recorridoEfectuadoA(buscarA.camino());
                  solucionBusqueda abrir = new solucionBusqueda(matrizTablero,posiciones,"Busqueda en Amplitud",2,buscarA.getObjetivo().getNivel(),buscarA.cantidadTotalNodosGenerados(),buscarA.getTiempoTotalBusqueda(),buscarA.isLlegoFinal(),buscarA.getObjetivo().getNivel(),buscarA.getObjetivo().getCosto());
                  abrir.show(true);
                  jButton2.setEnabled(false);
                  jLabel2.setVisible(false);
                  butSolucion.setEnabled(true);
                  jRadioButton1.setEnabled(true);
                  jRadioButton2.setEnabled(true);
                  jTextField1.setEnabled(true);
                  comboAlg.setEnabled(true);
                } catch (ExcepcionParada ex) {
                    System.out.println(ex.getMessage());
                    jLabel2.setVisible(false);
                    List<int[]> posiciones;
                    posiciones = recorridoEfectuadoA(buscarA.camino());
                    solucionBusqueda abrir = new solucionBusqueda(matrizTablero,posiciones,"Busqueda en Amplitud",2,buscarA.getObjetivo().getNivel(),buscarA.cantidadTotalNodosGenerados(),buscarA.getTiempoTotalBusqueda(),buscarA.isLlegoFinal(),buscarA.getObjetivo().getNivel(),buscarA.getObjetivo().getCosto());
                    abrir.show(true);
                    this.suspend(); 
               }
             }

            };
            hiloDeLaBusqueda.start();
            
        }

        if(this.comboAlg.getSelectedIndex()==3){

            //BUSQUEDA A*
            Thread hiloDeLaBusqueda = new Thread(){

                public void run(){
            
                    NodoE inicial = new NodoE(matrizTablero,0,0,0,0);
                    buscarE = new busquedaEstrella(inicial);
                try {
                  buscarE.buscarEstrella();
                  List<int[]> posiciones;
                  posiciones = recorridoEfectuadoE(buscarE.devolverCamino());
                  solucionBusqueda abrir = new solucionBusqueda(matrizTablero, posiciones,"Busqueda Estrella",3,buscarE.profundidadMaximaAlcanzada(),buscarE.getAbiertos().size(),buscarE.getTiempoTotalBusqueda(),buscarE.isEncontroSolucion(),buscarE.getObjetivo().getNivel(),buscarE.getObjetivo().getF());
                  abrir.show(true);
                  jButton2.setEnabled(false);
                  jLabel2.setVisible(false);
                  butSolucion.setEnabled(true);
                  jRadioButton1.setEnabled(true);
                  jRadioButton2.setEnabled(true);
                  jTextField1.setEnabled(true);
                  comboAlg.setEnabled(true);
                } catch (ExcepcionParada ex) {
                    System.out.println(ex.getMessage());
                    jLabel2.setVisible(false);
                    List<int[]> posiciones;
                    posiciones = recorridoEfectuadoE(buscarE.devolverCamino());
                    solucionBusqueda abrir = new solucionBusqueda(matrizTablero, posiciones,"Busqueda Estrella",3,buscarE.profundidadMaximaAlcanzada(),buscarE.getAbiertos().size(),buscarE.getTiempoTotalBusqueda(),buscarE.isEncontroSolucion(),buscarE.getObjetivo().getNivel(),buscarE.getObjetivo().getF());
                    abrir.show(true);
                    this.suspend();
                    
                }

                }

            };
            hiloDeLaBusqueda.start();
            
        }
        this.cantNivelesBusqueda = 0;
        }

        
    }//GEN-LAST:event_butSolucionActionPerformed

    private void radAleatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radAleatorioActionPerformed
        // TODO add your handling code here:
        this.seGenero = true;
        this.radPersonalizado.setSelected(false);
        this.aleatoria =true;
        this.personalizada =false;
        this.butGenerar.setEnabled(true);
    }//GEN-LAST:event_radAleatorioActionPerformed

    private void radPersonalizadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radPersonalizadoActionPerformed
        
        // OPCION CONFIGURACION PERSONALIZADA DEL TABLERO
        this.seGenero = false;
        this.radAleatorio.setSelected(false);
        this.radAleatorio.setEnabled(false);
        this.personalizada=true;
        this.aleatoria =false;
        this.butGenerar.setEnabled(false);
        opcionesBusqueda abrir = new opcionesBusqueda(this,true);
        //abrir.setAlwaysOnTop(true);
        abrir.show(true);

        if(abrir.isVolvi()){
            this.seGenero = true;
            this.radAleatorio.setEnabled(true);
            this.radAleatorio.setSelected(false);
            this.radPersonalizado.setEnabled(true);
            this.radPersonalizado.setSelected(false);
            this.butListo.setEnabled(false);
       }else{

            this.butListo.setEnabled(true);
        boolean negros;
        boolean blancos;
        int cantidadBlancos;
        negros = abrir.isNegros();
        blancos = abrir.isBlancos();
        cantidadBlancos = abrir.getCantidadBlancos();
        System.out.println(blancos);
        System.out.println("Cant bcos: "+cantidadBlancos);

        //actualizamos las variables globales del programa
        this.caballoBco = blancos;
        this.caballoNgo = negros;
        this.cantidadCaballosBlancos = cantidadBlancos;

        if(negros){
            this.caballoNgo = true;

            if(blancos){

            }else{
                System.out.println("Entre");


            }

        }else{


            if(this.caballoBco){
                Random aleatorio = new Random();
                int fCN;
                int cCN;
                fCN = aleatorio.nextInt(8);
                cCN = aleatorio.nextInt(8);
                Cuadro[fCN][cCN].caballo_blanco("caballo_negro");
                this.tableroPanel.repaint();

            }else{
                this.seGenero = true;
                matrizAleatoria obtenerla = new matrizAleatoria();
                System.out.println(this.cantidadCaballosBlancos);
                obtenerla.cargarAleatoriamente(false, this.cantidadCaballosBlancos);

                int [][] matricita;
                matricita = obtenerla.getMatriz();

                for(int i=0;i<8;i++){
                    for(int j=0;j<8;j++){
                        if(matricita[i][j]==2){
                            Cuadro[i][j].caballo_blanco("caballo_negro");
                            this.matrizTablero[i][j] = 2;
                        }
                        if(matricita[i][j]==1){
                            Cuadro[i][j].caballo_blanco("caballo_blanco");
                            this.matrizTablero[i][j] = 1;
                        }

                    }
                }
                this.tableroPanel.repaint();
            }
        }

        }       
    }//GEN-LAST:event_radPersonalizadoActionPerformed

    private void butListoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butListoActionPerformed
        // TODO add your handling code here:
        this.seGenero = true;
        this.radAleatorio.setEnabled(false);
        this.radPersonalizado.setEnabled(false);
        this.butGenerar.setEnabled(false);
        this.butListo.setEnabled(false);
        this.comboAlg.setEnabled(true);
        this.mostrarMatrizLogica();

    }//GEN-LAST:event_butListoActionPerformed

    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
        // TODO add your handling code here:
        this.jRadioButton2.setSelected(false);
    }//GEN-LAST:event_jRadioButton1ActionPerformed

    private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
        // TODO add your handling code here:
        this.jRadioButton1.setSelected(false);
        this.jTextField1.setEnabled(true);
    }//GEN-LAST:event_jRadioButton2ActionPerformed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        // TODO add your handling code here:
        acercaDe caja = new acercaDe();
        caja.show(true);
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        //PARAMOS EL ALGORITMO
        if(comboAlg.getSelectedIndex()==1){
            buscarP.setParar(true);
        }
        if(comboAlg.getSelectedIndex()==2){
            buscarA.setParar(true);
        }
        if(comboAlg.getSelectedIndex()==3){
            buscarE.setParar(true);
        }

        this.jButton2.setEnabled(false);
        this.comboAlg.setEnabled(true);


    }//GEN-LAST:event_jButton2ActionPerformed

   
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new tableroAjedrez().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton butGenerar;
    private javax.swing.JButton butListo;
    private javax.swing.JButton butSolucion;
    private javax.swing.JComboBox comboAlg;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JRadioButton radAleatorio;
    private javax.swing.JRadioButton radPersonalizado;
    private javax.swing.JPanel tableroPanel;
    // End of variables declaration//GEN-END:variables

    //eventos para el mouse 
    public void mouseClicked(MouseEvent e) {
        
    }

    public void mousePressed(MouseEvent e) {
       //MANEJO DE EVENTOS DE CLICK DEL RATON PARA PINTAR EN EL TABLERO
        System.out.println("Se hizo click en la posición "+e.getX()+" , "+e.getY());
        for(int x=0; x<8;x++){
            for(int y=0;y<8;y++){

                if(Cuadro[x][y].equals(e.getSource())){
                    
                   if(this.personalizada||this.aleatoria){
                       if(this.seGenero){
                        
                    }else{

                        if(this.aleatoria==false){
                            Cuadro[x][y].setBackground(Color.red);
    
                            if(this.caballoNgo){
                                Cuadro[x][y].caballo_blanco("caballo_negro");
                                this.matrizTablero[x][y]=2;
                                this.xcb = x;
                                this.xcn = y;
                                this.caballoNgo = false;

                                if(this.caballoBco){
                                    JOptionPane.showMessageDialog(null, "Ahora ubique todos los caballos blancos");
                                }else{
                                    matrizAleatoria obtenerla = new matrizAleatoria();
                                    obtenerla.cargarAleatoriamente(true, this.cantidadCaballosBlancos);
                                    obtenerla.colocarCaballoNegro(this.xcb, this.xcn);

                                    int [][] matricita;
                                    matricita = obtenerla.getMatriz();

                for(int i=0;i<8;i++){
                    for(int j=0;j<8;j++){
                        if(matricita[i][j]==2){
                            Cuadro[i][j].caballo_blanco("caballo_negro");
                            this.matrizTablero[i][j]=2;
                        }
                        if(matricita[i][j]==1){
                            Cuadro[i][j].caballo_blanco("caballo_blanco");
                            this.matrizTablero[i][j]=1;
                        }

                    }
                }
                this.seGenero = true;
                                   
                                }


                            }else{       
                              Cuadro[x][y].caballo_blanco("caballo_blanco");
                              this.matrizTablero[x][y]=1;
                            }
                        }
                    }
                   }
                }
            }
        }
        this.tableroPanel.repaint();      
    }

    public void mouseReleased(MouseEvent e) {
        
    }

    public void mouseEntered(MouseEvent e) {
        
    }

    public void mouseExited(MouseEvent e) {
       
    }

    public void mouseDragged(MouseEvent e) {
        
    }

    public void mouseMoved(MouseEvent e) {
       
    }

    /**
     * @return the matrizTablero
     */
    public int[][] getMatrizTablero() {
        return matrizTablero;
    }

    /**
     * @param matrizTablero the matrizTablero to set
     */
    public void setMatrizTablero(int[][] matrizTablero) {
        this.matrizTablero = matrizTablero;
    }

    
    public void mostrarMatrizLogica(){
        System.out.println("Matriz Lógica del Tablero");
        for(int i=0;i<8;i++){
            for(int j=0;j<8;j++){
                System.out.print(this.matrizTablero[i][j]);
            }
            System.out.println();
        }
        System.out.println();

    }
    //Metodos auxiliares para armar la lista que le pasamos al frame sgte para que pinte el recorrido
    public List<int[]> recorridoEfectuado(List<Nodo> camino){

        List<int[]> aDevolver;
        aDevolver = new ArrayList();

        for(int i=0;i<camino.size();i++){

            int[] elm;
            elm = new int[2];

            int[][] matriz;
            matriz = camino.get(i).getPosicion();

            for(int j=0;j<8;j++){
                for(int k=0;k<8;k++){
                    if(matriz[j][k]==2){
                        elm[0]=j;
                        elm[1]=k;
                    }

                }
            }
            aDevolver.add(elm);


        }

        return aDevolver;
    }
    public List<int[]> recorridoEfectuadoA(List<NodoA> camino){
        List<int[]> aDevolver;
        aDevolver = new ArrayList();

        for(int i=camino.size()-1;i>=0;i--){

            int[] elm;
            elm = new int[2];

            int[][] matriz;
            matriz = camino.get(i).getPosicion();

            for(int j=0;j<8;j++){
                for(int k=0;k<8;k++){
                    if(matriz[j][k]==2){
                        elm[0]=j;
                        elm[1]=k;
                    }

                }
            }
            aDevolver.add(elm);
            }

        return aDevolver;

    }
    public List<int[]> recorridoEfectuadoE(List<NodoE> camino){
        List<int[]> aDevolver;
        aDevolver = new ArrayList();

        for(int i=camino.size()-1;i>=0;i--){

            int[] elm;
            elm = new int[3];

            int[][] matriz;
            matriz = camino.get(i).getPosicion();

            for(int j=0;j<8;j++){
                for(int k=0;k<8;k++){
                    if(matriz[j][k]==2){
                        elm[0]=j;
                        elm[1]=k;
                    }

                }
            }

            elm[2] = camino.get(i).getF();
            aDevolver.add(elm);
            }

        return aDevolver;
    }

}
